#!/bin/bash
# RS-485 Fullduplex loopback test 
# A-B and X-Y need to be a loop

RS485_PORT="/dev/ttymxc0"
OPTIND=1 
evt_design=0

show_help()
{
  echo "Usage: rs485_chk [OPTIONs]"
  echo "OPTIONS:"
  echo "	-h	help"
  echo "	-e	For EVT circuit design test"
}


check_rs485()
{
  # gpio32 is Half/Full-duplex, 0 is fullduplex
  # gpio40 is RE_N (In EVT design is DE)
  # gpio41 is DE (In EVT design is RE_N)
  if [[ evt_design -eq 1 ]]; then
    if [[ ! -d /sys/class/gpio/gpio32 ]]; then
      echo "Init RS485 Fullduplex"
      echo 32 > /sys/class/gpio/export
      echo 40 > /sys/class/gpio/export
      echo 41 > /sys/class/gpio/export
    fi
    echo out > /sys/class/gpio/gpio32/direction
    echo out > /sys/class/gpio/gpio40/direction
    echo out > /sys/class/gpio/gpio41/direction
    echo 0 > /sys/class/gpio/gpio32/value
    echo 1 > /sys/class/gpio/gpio40/value
    echo 0 > /sys/class/gpio/gpio41/value
    res=$($MYPATH/uart-loopback -c 1 $RS485_PORT | grep "PASS")
  else
    if [[ ! -d /sys/class/gpio/gpio32 ]]; then
      echo "Init RS485 Fullduplex"
      echo 32 > /sys/class/gpio/export
      echo 40 > /sys/class/gpio/export
    fi
    echo out > /sys/class/gpio/gpio32/direction
    echo out > /sys/class/gpio/gpio40/direction
    echo 0 > /sys/class/gpio/gpio32/value
    echo 0 > /sys/class/gpio/gpio40/value
    res=$($MYPATH/rs485-loopback $RS485_PORT 115200 8N1 10 U | grep "PASS")
  fi

  if [ $res = "PASS" ]; then
    echo "PASS"
  else
    (>&2 echo "FAIL")	
  fi
}

MYPATH=$(dirname $0)


while getopts "h?e" opt; do
  case "$opt" in
    h|\?)
      show_help
      exit 0
      ;;
    e)
      evt_design=1
      ;;
    esac
done

shift $((OPTIND-1))
[ "${1:-}" = "--" ] && shift

check_rs485

